package com.sfx.concurrent.demo.cas.atomic.reference;

import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-31
 * Time: 8:55
 */
public class AtomicTest {


    public static void main(String[] args) {
        AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<>(1, 0);
        System.out.println("初始ref : " + stampedReference.getReference());
        System.out.println("初始stamp : " + stampedReference.getStamp());

        // 自增之后
        while(true) {
            boolean isSuccess = stampedReference.compareAndSet(1, 10000, stampedReference.getStamp()
                    , stampedReference.getStamp() + 1);
            if(isSuccess) {
                System.out.println("之后ref : " + stampedReference.getReference());
                System.out.println("之后stamp : " + stampedReference.getStamp());
                return;
            }
        }
    }


    public static void main2(String[] args) {
        AtomicIntegerFieldUpdater<User> updater = AtomicIntegerFieldUpdater.newUpdater(User.class, "age");
        User user = new User("1", "ppp");
        System.out.println(updater.get(user));
        updater.getAndIncrement(user);
        System.out.println(updater.get(user));
    }

    public static void main1(String[] args) {
        AtomicReference<User> atomicReference = new AtomicReference<>();
        // 原始user对象
        User user = new User("1", "sfx");
        // 设置原子类初始值
        atomicReference.set(user);
        // 获取
        System.out.println("获取user : " + atomicReference.get());
        System.out.println("==================更新之后=======================");
        // 更新的User对象
        User updateUser = new User("2", "sb高一凡");
        // 进行更新
//        atomicReference.compareAndSet(user, updateUser);
//        System.out.println("获取user : " + atomicReference.get());

        atomicReference.compareAndSet(user, updateUser);
        System.out.println("获取user : " + user);
        System.out.println("updateUser : " + updateUser);
    }
}
